import type { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import axios from 'axios'
import {userStore} from '../stores/modules/user'
import { showFailToast } from 'vant';
 // import { localStorage } from '@/utils/local-storage'
// import md5 from './md5'
// import { getParams } from './tool'


// 创建 axios 实例
const request = <AxiosInstance>axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 6000, // 请求超时时间
})

export type RequestError = AxiosError<{
  message?: string
  result?: any
  errorMessage?: string
}>
const delay = (time: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(1);
    }, time * 1000);
  });
};
// 异常拦截处理器
const errorHandler = async (error: RequestError): Promise<any> => {
  try {
    let config: any
    if (error.config){ config = error.config}else if (error.response && error.response.config) config = error.response.config
    if (config.reTry > 0) {
      await delay(3);
      return request({ url: config.url, method: config.method, data: JSON.parse(config.data), reTry: config.reTry - 1 } as any)
    } else {
      showFailToast(error.response?.data.message)
      return Promise.reject(error)
    }
  } catch (err) {
   
    return Promise.reject(error)
  }
}

// 请求拦截器
const requestHandler = (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig | Promise<InternalAxiosRequestConfig> => {
  
  // const token = localStorage.get("token")
  // const timeStamp = new Date().getTime();
  // if (token) {
   config.headers["Authorization"] = userStore().sign;
   config.headers["Address"] = userStore().address;
  // }
  // config.data["timestamp"] = timeStamp
  // config.headers["X-Timestamp"] = timeStamp
  // config.headers["X-Language"] = config.data["language"]
  // config.headers["X-Sign"] = config.data["sign"]
  if (config.method !== 'post') {
    config.params = config.data
  }
  return config
}

// Add a request interceptor
request.interceptors.request.use(requestHandler, errorHandler)

// 响应拦截器
const responseHandler = (response: AxiosResponse<any>) => {
   if (response.data.code === 10000 || response.data.code === 200) {
     return Promise.resolve(response.data.data)
  } else {

    return Promise.reject(response.data.message)
  }
}

// Add a response interceptor
request.interceptors.response.use(responseHandler, errorHandler)

export const HttpServer = <T>(url: string, data: any = {}, method: string = "post", reTry: number = 0) => {
  return request<T>({ url, method, data, reTry } as any) as Promise<T>
}
